package main

import (
	"bytes"
	"encoding/base64"
	"fmt"
	"os"
	"os/exec"
	"regexp"
	"strconv"
	"time"
)

var sum float32
var vacation int
var err error

var workDays int
var monthDays map[time.Month]int = map[time.Month]int{
	time.January:   31,
	time.February:  28,
	time.March:     31,
	time.April:     30,
	time.May:       31,
	time.June:      30,
	time.July:      31,
	time.August:    31,
	time.September: 30,
	time.October:   31,
	time.November:  30,
	time.December:  31,
}

func init() {
	workDays = calDate()
}
func main() {
	var dir *os.File
	var path string
	if len(os.Args) != 3 {
		fmt.Println("请使用run.sh")
		usage()
		os.Exit(-1)
	}
	var err error
	fmt.Printf("每月假期采用值 :%v\n", os.Args[1])
	vacation, err = strconv.Atoi(os.Args[1])
	printErr("strconv error :", err)
	path = os.Args[2]

	dir, err = os.Open(path)
	printErr("open dir ", err)

	os.Chdir(path)
	fetchmail(path)

	fileinfo, err := dir.Readdir(-1)
	printErr("readdir", err)

	for _, v := range fileinfo {
		file, err := os.OpenFile(v.Name(), os.O_RDONLY, 0444)
		printErr("open file error", err)
		sum += handleFile(file)
		//		fmt.Println(v.Name())
		//		fmt.Printf("sum = %v\n", sum)
	}
	total := float32((workDays - vacation) * 7)
	fmt.Printf("已用工时为:%v\n当月工作时间为:%v\n当月总工时为:%v\n", sum, workDays-vacation, total)
	fmt.Printf("比率:%.2f%%\n", sum/total*100)

}

func fetchmail(path string) {
	f := exec.Command("fetchmail", "-a")
	f.Stdout = os.Stdout
	err = f.Run()
	if err != nil {
		printErr("Run command", err)
	}

}

var regLine *regexp.Regexp = regexp.MustCompile("消耗 [0-9]+\\.[0-9]")
var regNum *regexp.Regexp = regexp.MustCompile("[0-9]+\\.[0-9]")

func handleFile(file *os.File) (ret float32) {
	var fBufer bytes.Buffer
	_, err := fBufer.ReadFrom(file)
	if err != nil {
		printErr("err : %v\n", err)
	}

	var enCodeBytes []byte
	for {
		l, err := fBufer.ReadBytes('\n')
		if err != nil {
			break
		}
		if l[0] == '\n' {
			for {
				l, err = fBufer.ReadBytes('\n')
				if err != nil {
					break
				}
				enCodeBytes = append(enCodeBytes, l...)
			}
			break
		}
	}
	deCodeBytes := make([]byte, len(enCodeBytes))
	_, err = base64.StdEncoding.Decode(deCodeBytes, enCodeBytes)
	if err != nil {
		printErr("Decode :", err)
	}
	//	fmt.Println(string(deCodeBytes))

	all := regLine.FindAll(deCodeBytes, -1)
	for _, l := range all {
		a, b := 0, 0
		r := regNum.Find(l)
		if len(r) == 3 {
			a, _ = strconv.Atoi(string(r[0]))
			b, _ = strconv.Atoi(string(r[2]))
			ret += float32(a) + float32(b/10)
		} else if len(r) == 4 {
			t, _ := strconv.Atoi(string(r[0]))
			a, _ = strconv.Atoi(string(r[1]))
			a = t*10 + a
			b, _ = strconv.Atoi(string(r[3]))
			ret += float32(a) + float32(b/10)
		}

	}
	//fmt.Printf("file %v ret: %v\n", file.Name(), ret)
	return
}

func calDate() (ret int) {
	now := time.Now()
	localocation, _ := time.LoadLocation("Local")
	firstDay := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, localocation)
	//	lastDay := time.Date(now.Year(), now.Month(), monthDays[now.Month()], 0, 0, 0, 0, localocation)

	if now.Month() == time.February {
		if now.Year()%4 == 0 || now.Year()%100 == 0 && now.Year()%400 == 0 {
			ret = 29
		} else {
			ret = 28
		}

	} else {
		ret = monthDays[now.Month()]
	}
	if firstDay.Weekday() == time.Saturday {
		ret = ret - 8 - 2
	} else if firstDay.Weekday() == time.Sunday {
		ret = ret - 8 - 1
	} else {
		ret = ret - 8
	}
	return
}

const usageString string = `Usage:
edit the run.sh for your $MAILPATH ,$COUNT and $PASSWD
use "bash run.sh"
`

func usage() {
	fmt.Println(usageString)
}
func printErr(info string, err error) {
	if err != nil {
		fmt.Printf("%s errors is: %v\n", info, err)
		os.Exit(-1)
	}
}
